<?php

declare(strict_types=1);

namespace App\Activity\Task;

use App\Activity\Model\ActivityModel;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * @Crontab(name="SeckillTask", rule="*\/30 * * * * *", callback="execute", memo="定时检测修改秒杀活动的状态")
 */
class SeckillTask
{
    /**
     * @Inject
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    protected $redis;

    public function __construct()
    {
        $this->redis = $this->container->get(RedisFactory::class)->get('seckill');
    }

    public function execute()
    {
        $currentDate = date('Y-m-d', time());   // 2020-12-15

        $operation = [];    // 收集要变更为进行中的活动 ID
        $closed = [];    // 收集要变更为已关闭的活动 ID

        // 获取今天未被禁用的秒杀活动，并根据当前时间判断活动状态是否需要改变
        $seckillList = ActivityModel::query()
            ->where('activityType', 4)
            ->where('is_deleted', 0)
            ->whereIn('status', [1,2])
            ->whereDate('begin_date', $currentDate)
            ->get(['activityID', 'status','begin_date','activity_prams']);

        if($seckillList->isEmpty()){
            return;
        }

        // 拼接每个活动的时间
        foreach($seckillList as $key => $val){
            $actTime = json_decode($val['activity_prams'], true);
            $checkTime = $this -> checkTime($currentDate, $actTime['start_time'], $actTime['end_time']);
            if($checkTime == 2){
                array_push($operation, $val['activityID']);
            }elseif ($checkTime == 3){
                array_push($closed, $val['activityID']);
            }
        }

        if(!empty($operation)){
            ActivityModel::query()->whereIn('activityID', $operation)->update(['status' => 2]);
        }

        // 构造一个当天 23:58:00 的时间戳
//        $closeTime = strtotime(date('Y-m-d 17:34:00',time()));

        if(!empty($closed)){
            ActivityModel::query()->whereIn('activityID', $closed)->update(['status' => 3]);
        }

    }

    /**
     * @return bool
     *
     * 活动已过期，变更为禁用
     * 活动未开始，保持为未生效
     * 活动进行中，变更为进行中
     *
     * 判断当前时间是否处于给定的时间段中
     * @param $day
     * @param $start
     * @param $end
     *
     * @return bool     处于 true，不处于 false
     */
    public function checkTime($day, $start, $end)
    {
        $timeBegin = strtotime($day.' '.$start);
        $timeEnd = strtotime($day.' '.$end);
        $currentTime = time();
        if($currentTime >= $timeBegin && $currentTime <= $timeEnd){
            return 2;   // 进行中
        }elseif ($currentTime < $timeBegin){
            return 1;   // 活动未开始
        }elseif ($currentTime > $timeEnd){
            return 3;   // 活动已结束
        }

    }
}
